package com.zsd.android.glidelib.resource;

import android.graphics.Bitmap;

/**
 * 对Bitmap的封装
 */
public class Value {

    private static volatile Value instance;
    private Bitmap mBitmap;
    //使用计数, 使用一次+1
    private int count;
    private ValueCallback callback;
    //定义key
    private String key;

    private Value() {

    }

    public static Value getInstance() {
        Value value = instance;
        if (value == null) {
            synchronized (Value.class) {
                if (value == null) {
                    value = new Value();
                    instance = value;
                }
            }
        }
        return value;
    }

    /**
     * todo 使用一次就加一
     */
    public void useAction() {
        if (mBitmap == null) {
            return;
        }
        if (mBitmap.isRecycled()) {
            return;
        }
        count++;
    }

    /**
     * todo 使用完成就减一
     */
    public void nonUseAction() {
        if (mBitmap == null) {
            return;
        }
        if (mBitmap.isRecycled()) {
            return;
        }
        count--;
        if (count <= 0 && callback != null) {
            //回调告诉外界不再使用了
            callback.valueNonUseListener(key, this);
        }
    }

    /**
     * todo 释放
     */
    public void recycleBitmap() {
        if (count > 0) {
            return;
        }
        if (mBitmap.isRecycled()) {
            return;
        }
        mBitmap.recycle();
        instance = null;
        System.gc();
    }

    public Bitmap getBitmap() {
        return mBitmap;
    }

    public void setBitmap(Bitmap mBitmap) {
        this.mBitmap = mBitmap;
    }

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }

    public ValueCallback getCallback() {
        return callback;
    }

    public void setCallback(ValueCallback callback) {
        this.callback = callback;
    }

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }
}
